package com.example.demo.command;

import com.example.demo.entity.NotificationConfig;
import com.example.demo.repository.NotificationConfigRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class NotificationConfigCommand {

    private final NotificationConfigRepository repository;

    @Autowired
    public NotificationConfigCommand(NotificationConfigRepository repository) {
        this.repository = repository;
    }

    public String handleSetNotificationChannel(String guildId, String channelId, String eventType) {
        try {
            // 查找现有配置
            NotificationConfig config = repository.findByGuildIdAndEventTypeAndEnabled(guildId, eventType, true)
                .stream().findFirst().orElse(new NotificationConfig());

            // 更新或创建新配置
            config.setGuildId(guildId);
            config.setChannelId(channelId);
            config.setEventType(eventType);
            config.setEnabled(true);
            config.setUpdatedAt(System.currentTimeMillis());
            
            if (config.getCreatedAt() == null) {
                config.setCreatedAt(System.currentTimeMillis());
            }

            repository.save(config);
            return String.format("已将 %s 事件的通知频道设置为当前频道", getEventTypeDisplay(eventType));
        } catch (Exception e) {
            log.error("设置通知频道时出现错误", e);
            return "设置通知频道失败，请稍后重试";
        }
    }

    private String getEventTypeDisplay(String eventType) {
        switch (eventType) {
            case "voice_channel_join":
                return "语音频道加入";
            default:
                return eventType;
        }
    }
}